const path = require('path');
var fs = require("fs");
var uuid = require('node-uuid');
var async = require('async');
const {ipcRenderer} = require('electron');

const MaxTagCount = 8;
const SaveText = "保存";

var tagconfig = [
    ["Brackets","Coda","Dreamweaver","Espresso","jEdit"],
    ["Komodo Edit","Notepad++","Sublime Text 2"],
    ["Brackets","Coda","Dreamweaver","Espresso","jEdit"],
    ["Komodo Edit","Notepad++","Sublime Text 2"],
    ["Brackets","Coda","Dreamweaver","Espresso","jEdit"],
    ["Komodo Edit","Notepad++","Sublime Text 2"],
    ["Brackets","Coda","Dreamweaver","Espresso","jEdit"],
    ["Komodo Edit","Notepad++","Sublime Text 2"]
];

var holder = document.getElementById('drag-drop-container');
function setHolderPink(){
    holder.style.backgroundColor = 'pink';
}
holder.ondragover = () => {
    holder.style.backgroundColor = 'red';
    return false;
};
holder.ondragleave = () => {
    setHolderPink();
    return false;
};
holder.ondragend = () => {
    setHolderPink();
    return false;
};
holder.ondrop = (e) => {
    e.preventDefault();
    setHolderPink();
    for (let f of e.dataTransfer.files) {  
        var stat = fs.statSync(f.path);        
        if(stat.isDirectory()){
            AddDirFiles(f.path);
        }
        else{
            AddFile(f.path);
        }            
    }
    SetupFileList();
}

SetupDataList();
function SetupDataList(){
    var htmls = "";
    for(var i = 0; i < MaxTagCount; i++){
        htmls += "<datalist id='ide{0}'>".format(i+1);
        var data = tagconfig[i];
        for(var j = 0; j < data.length; j++){
            htmls += "<option value='{0}' />".format(data[j]);
        }
        htmls += "</datalist>";
    }
    document.getElementById("datalist").innerHTML = htmls;
}

function AddDirFiles(dirPath){
    let subDirPath = fs.readdirSync(dirPath);
    subDirPath.forEach(function(i, index){        
        var subPath = path.join(dirPath, i);
        let stat = fs.statSync(subPath);
        if(stat.isDirectory()){
            AddDirFiles(subPath);
        }else{
            AddFile(subPath);
        }
    });
}

var audiofiles = [];
class AudioFile{
    constructor(filename){
        this.name = filename;
        this.dirname = path.dirname(filename);
        this.basename = path.basename(filename);
        this.suffix = path.extname(filename);
        this.uuid = uuid.v1();
        this.tempfilename = path.join(this.dirname,this.uuid+this.suffix);
        this.basenamewithoutext = this.basename.substring(0,this.basename.length - this.suffix.length);
        var arr = this.basenamewithoutext.split('_');
        this.tags = [];
        for(var i = 0; i < MaxTagCount;i ++){
            this.tags.push('');
        }
        for(var i = 0; i < arr.length; i++){
            if(i < MaxTagCount && !arr[i].isNumber()){
                this.tags[i] = arr[i];
            }
        }
        this.index = 0;
        this.count = 0;
    }

    newfilename(){
        var arr = new Array();
        for(var i = 0; i < this.tags.length; i++){
            if(this.tags[i].length > 0){
                arr.push(this.tags[i]);
            }
        }
        return arr.join('_');
    }
    
    fullnewfilename(){
        return this.saveasfilename(this.dirname);
    }

    saveasfilename(dir){
        var suffix = this.count > 1 ? '_'+ this.index.toString().padStart(2,0) : '';
        var filename = this.newfilename() + suffix + this.suffix;
        return path.join(dir,filename);
    }

    replace(ignoreCase,column,fromValue,toValue){
        if(ignoreCase){
            this.tags[column] = this.tags[column].replace(new RegExp(fromValue.toLowerCase(), 'gi'), toValue);
        }else{
            this.tags[column] = this.tags[column].replace(fromValue, toValue);
        } 
    }

    replaceAll(ignoreCase,fromValue,toValue){
        for(var i = 0; i < this.tags.length; i++){
            this.replace(ignoreCase,i,fromValue,toValue);               
        }
    }
}

function AddFile(filename){
    console.log(filename);
    for(var i = 0; i < audiofiles.length;i++){
        var file = audiofiles[i];
        if(file.name == filename){
            return;
        }
    }
    audiofiles.push(new AudioFile(filename));
}

function SetupFileList(){    
    var theme = ["","success","error","warning","info"];
    var itemTemplate = "<tr class={7}>\
    <td style='padding:0px;' id='{10}'>\
        <span style='width:100%;'><span>{0}</span></span>\
    </td>\
    <td style='padding:0px;'>\
      <input class='name-tag' line='{10}' index='0' globalidx='{9}' id='global.tag.{9}' type='text' value='{1}' list='ide1' />\
    </td>\
    <td style='padding:0px;'>\
      <input class='name-tag' line='{10}' index='1' globalidx='{10}' id='global.tag.{10}' type='text' value='{2}' list='ide2' />\
    </td>\
    <td style='padding:0px;'>\
        <input class='name-tag' line='{10}' index='2' globalidx='{11}' id='global.tag.{11}' type='text' value='{3}' list='ide3' />\
    </td>\
    <td style='padding:0px;'>\
        <input class='name-tag' line='{10}' index='3' globalidx='{12}' id='global.tag.{12}' type='text' value='{4}' list='ide4' />\
    </td>\
    <td style='padding:0px;'>\
        <input class='name-tag' line='{10}' index='4' globalidx='{13}' id='global.tag.{13}' type='text' value='{5}' list='ide5' />\
    </td>\
    <td style='padding:0px;'>\
        <input class='name-tag' line='{10}' index='5' globalidx='{14}' id='global.tag.{14}' type='text' value='{6}' list='ide6' />\
    </td>\
    <td style='padding:0px;'>\
        <input class='name-tag' line='{10}' index='6' globalidx='{15}' id='global.tag.{15}' type='text' value='{7}' list='ide7' />\
    </td>\
    <td style='padding:0px;'>\
        <input class='name-tag' line='{10}' index='7' globalidx='{16}' id='global.tag.{16}' type='text' value='{8}' list='ide8' />\
    </td>\
    <td style='padding:0px;'>\
        <button class='btn-delete-file' line='{10}'>删除</button>\
    </td>\
    </tr>";

    var htmls = "";
    ForeachFile((file,i)=>{
        htmls += itemTemplate.format(
            file.basename, 
            file.tags[0],
            file.tags[1],
            file.tags[2],
            file.tags[3],
            file.tags[4],
            file.tags[5],
            file.tags[6],
            file.tags[7],
            theme[i % 5], 
            i,
            i * 6,
            i * 6 + 1,
            i * 6 + 2,
            i * 6 + 3,
            i * 6 + 4,
            i * 6 + 5,
            i * 6 + 6,
            i * 6 + 7);
    });
    document.getElementById("dragfiles").innerHTML = htmls; 
    $("input.name-tag").bind("change", function () {
        var line = $(this).attr('line');
        var index = $(this).attr('index');
        var file = audiofiles[line];
        console.log("line : ", line);
        file.tags[index] = this.value;
        audiofiles[line] = file;
    });   
    $("button.btn-delete-file").bind("click", function () {
        var line = $(this).attr('line');
        audiofiles.splice(line, 1);
        //刷新界面
        SetupFileList();
    })
}

function AppendLogs(log){
    //不要删除，当发布版本有问题时，打开这个注释可以帮助调试
    // var htmlTemplate = "<td style='padding:0px;'>\
    //     <span style='width:100%;'><span>{0}</span></span>\
    // </td>"
    // var html = htmlTemplate.format(log);
    // document.getElementById("files").innerHTML += html;
}

function copy(src, dst) {
    AppendLogs("copy {0} -> {1}".format(src,dst));
    fs.createReadStream(src).pipe(fs.createWriteStream(dst));
}

function FillIndexToFiles(){
    var map = new Map();
    ForeachFile((file,i)=>{
        var filename = file.newfilename();
        var index = 0;
        if(map.has(filename)){
            index = map.get(filename) + 1;
            file.count = index;
        }else{
            file.count = 1;
            index = 1;
        }
        map.set(filename,index);
        file.index = index;
        audiofiles[i] = file;
        AppendLogs("{0} = {1}".format(index,filename));
    });
}

function RenameAllFile(button){
    FillIndexToFiles();

    async.waterfall([
        (callback) =>{
            ParseAllFile(RenameTempFile,(err)=>{
                callback(err);
            });
        },
        (callback) =>{
            ParseAllFile(RenameFile,(err)=>{
                callback(err);
            });
        },
        (callback) =>{
            //已经改了名字了，更新一下记录的名字，避免再次改名会失败的bug
            ForeachFile((file,i)=>{
                file.name = file.fullnewfilename();   
                audiofiles[i] = file;
            });
            callback(null);
        }
    ],(err)=>{
        if(err){
            AppendLogs(err);
        }
    });

    button.innerText = SaveText;
}

function ForeachFile(cb){
    for(var i = 0; i < audiofiles.length;i++){
        cb(audiofiles[i],i);
    }
}

function ParseAllFile(rename,finish){
    async.forEach(audiofiles,(i,cb) =>{
        rename(i,(err)=>{
            cb(err);
        })
    },(err)=>{

        finish(err);
    });
}

function RenameTempFile(file,cb){
    console.log('rename temp',file.name,file.tempfilename);
    AppendLogs("rename {0} -> {1}".format(file.name,file.tempfilename));
    cb(ipcRenderer.sendSync('rename', {from:file.name,to:file.tempfilename}));
}

function RenameFile(file, cb){
    var tofilename = file.fullnewfilename();
    console.log('rename real',file.tempfilename,tofilename);
    AppendLogs("rename {0} -> {1}".format(file.tempfilename,tofilename));
    cb(ipcRenderer.sendSync('rename', {from:file.tempfilename,to:tofilename}));
}



$("#btn-clean").bind("click", ()=>{
    audiofiles = [];
    SetupFileList();
    document.getElementById("btn-save").innerText = SaveText;
});

$("#btn-saveas").bind("click", ()=>{
    let electron = require('electron');
    const { dialog } = electron.remote;
    // 打开选择文件夹对话框,非模态
    dialog.showOpenDialog(null, {
        properties: ['openDirectory'],
    }, function(dirPath) {
        FillIndexToFiles();

        ForeachFile((file,i)=>{
            var filename = file.saveasfilename(dirPath[0]);   
            console.log(filename);
            copy(file.name,filename);
            file.name = filename;
            audiofiles[i] = file;
        });
    });
});

$("#btn-save").bind("click", ()=>{
    RenameAllFile(this);
});

var replaceColumn = 0;//0=全部列、1=第一列...
$("#selectColumn").bind("change", ()=>{
    replaceColumn = document.getElementById("selectColumn").value;
});

$("#btnReplace").bind("click", ()=>{
    var fromValue = document.getElementById("inputFrom").value;
    var toValue = document.getElementById("inputTo").value;

    var ig = ignoreCase();
    ForeachFile((file,i)=>{
        if(replaceColumn == 0){//全部列
            file.replaceAll(ig,fromValue,toValue);
        }else{//指定列
            file.replace(ig,replaceColumn - 1,fromValue,toValue);
        }        
        audiofiles[i] = file;
    });

    SetupFileList();
})

function ignoreCase(){
    return $("#wholeWord").hasClass("btndisable");
}

$("#ignoreCase").bind("click", ()=>{
    $("#ignoreCase").removeClass("btndisable");
    $("#wholeWord").addClass("btndisable");
});

$("#wholeWord").bind("click", ()=>{
    $("#wholeWord").removeClass("btndisable");
    $("#ignoreCase").addClass("btndisable");
});

/*
增加有关焦点切换的快捷键操作
*/    
ipcRenderer.on('move-focus',(event,arg) =>{
    var focus = document.activeElement;
    if(focus == null){
        return;
    }
    var curPos = parseInt(focus.getAttribute("globalidx")); 
    switch(arg){
        case 'left':    curPos -= 1;break;
        case 'right':   curPos += 1;break;
        case 'up':      curPos -= 6;break;
        case 'down':    curPos += 6;break;
        default:break;
    };
    //激活下面的输入框
    var next = document.getElementById('global.tag.' + curPos);
    if(next){
        next.focus();
    }
})

